/**
 *
 */
package com.py.credit.controller;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.ConcernedSubject;
import com.py.credit.entity.MsgContentEntity;
import com.py.credit.entity.MsgDetailEntity;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.XyjgDrqydf;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.CreditConcernedTableFieldsEnum;
import com.py.credit.service.*;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.FileUtils;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.helper.HttpServletHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 *
 * 信用关注
 *
 * @author dd
 *
 */

@RestController
@RequestMapping(value = "/concerned")
public class CreditConcernedController {

    private final static String FRONT_TABLE_CREDIT_CONCERNED_ID = "creditConcernedTable";

    @Autowired
    private CreditConcernedService creditConcernedService;

    @Autowired
    private RemoteBaseService remoteBaseService;

    @Autowired
    private ScontentService sContentService;

    @Autowired
    private ShareLogService shareLogService;

    @Autowired
    private SSearchService sSearchService;

    @RequestMapping("/add.json")
    public RestServiceResult<Object> add(ConcernedSubject record, HttpServletRequest request) {

        RestServiceResult<Object> res = new RestServiceResult<Object>();

        String level = record.getLevel();

        String subjectName = record.getSubjectName();

        if (StringUtils.isBlank(subjectName) || StringUtils.isBlank(level)) {

            res.setCode(-1);
            res.setMsg("企业名和关注等级不能为空！");
        } else {

            RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

            if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

                SysUser userInfo = user.getData();

                if (null != userInfo && userInfo.getId() != null) {

                    if (creditConcernedService.exsit(subjectName, userInfo.getId())) {

                        res.setCode(-1);
                        res.setMsg("企业:【" + subjectName + "】已经关注！");
                    } else {

                        record.setUserId(userInfo.getId());

                        creditConcernedService.add(record);
                    }

                } else {

                    res.setCode(-1);
                    res.setMsg("未获取到当前用户信息！");

                    ExceptionLogger.error("CreditConcernedController#add", "未获取到当前用户信息！");
                }

            } else {

                res.setCode(-1);
                res.setMsg("未获取到当前用户信息！");

                ExceptionLogger.error("CreditConcernedController#add", "未获取到当前用户信息！");
            }
        }

        return res;
    }

    @RequestMapping("/batchAdd.json")
    public RestServiceResult<Object> batchAdd(@RequestParam(value = "file") CommonsMultipartFile file,
                                              HttpServletRequest request) throws IOException {

        if (file == null) {

            throw new ServiceException("上传文件不得为空");

        }

        RestServiceResult<Object> res = new RestServiceResult<Object>();
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo && userInfo.getId() != null) {

                Map<String, Integer> add = creditConcernedService.add(file, userInfo.getId());

                res.setData(add);

            } else {

                res.setCode(-1);
                res.setMsg("未获取到当前用户信息！");

                ExceptionLogger.error("CreditConcernedController#add", "未获取到当前用户信息！");
            }

        } else {

            res.setCode(-1);
            res.setMsg("未获取到当前用户信息！");

            ExceptionLogger.error("CreditConcernedController#add", "未获取到当前用户信息！");
        }

        return res;
    }

    @RequestMapping("/getQyname.json")
    public RestServiceResult<List<String>> getQyname(@RequestParam(value = "name") String name) {

        List<String> names = creditConcernedService.getUniqueByName(name);

        return new RestServiceResult<List<String>>(names);

    }

    @RequestMapping("/getList.json")

    public RestServiceResult<List<Map<String, Object>>> getList(
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
            HttpServletRequest request) {

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        String[] configColumns = null;

        RestServiceResult<List<Map<String, Object>>> res = new RestServiceResult<List<Map<String, Object>>>();

        List<Map<String, Object>> tableList = new ArrayList<Map<String, Object>>();

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo && userInfo.getId() != null) {

                configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_CREDIT_CONCERNED_ID);

                List<String> showColumns = (configColumns == null || configColumns.length == 0)
                        ? CreditConcernedTableFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);

                String[] additionalColumns = {"ID", "tybm", "checkStatus"};

                tableList = creditConcernedService.getByConditionForPage(userInfo.getId(), showColumns,
                        additionalColumns, condition, page);

                res.setCount(page.getTotalCount());
                res.setData(tableList);
            } else {

                res.setCode(-1);
                res.setMsg("未获取到当前用户信息！");

                ExceptionLogger.error("CreditConcernedController#getList", "未获取到当前用户信息！");
            }

        } else {

            res.setCode(-1);
            res.setMsg("未获取到当前用户信息！");

            ExceptionLogger.error("CreditConcernedController#getList", "未获取到当前用户信息！");
        }

        return res;

    }

    @RequestMapping("/getAdvancedConditionColumns.json")
    public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {

        return new RestServiceResult<List<OptionalColumn>>(
                CreditConcernedTableFieldsEnum.getAdvancedConditionColumns());

    }

    @RequestMapping("/getOptionalColums.json")
    public RestServiceResult<List<OptionalColumn>> getOptionalColums() {

        return new RestServiceResult<List<OptionalColumn>>(CreditConcernedTableFieldsEnum.getOptionalColumns());

    }

    @RequestMapping("/addColumns.json")
    public RestServiceResult<Object> addColumns(@RequestParam(value = "columns", required = true) String[] columns,
                                                HttpServletRequest request) {

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo && userInfo.getId() != null) {

                MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_CREDIT_CONCERNED_ID, columns);
            } else {

                ExceptionLogger.error("CreditConcernedController#addColumns", "未获取到当前用户信息！");
            }

        } else {

            ExceptionLogger.error("CreditConcernedController#addColumns", "未获取到当前用户信息！");
        }

        return new RestServiceResult<Object>();

    }

    @RequestMapping("/export.json")
    public void export(@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
                       @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
                       HttpServletResponse response, HttpServletRequest request) throws IOException {
        page.setLimit(1000);

        List<String> showColumns = JSONArray.parseArray(columnEN, String.class);

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        List<Map<String, Object>> tableList = new ArrayList<Map<String, Object>>();

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo && userInfo.getId() != null) {

                tableList = creditConcernedService.getByConditionForPage(userInfo.getId(), showColumns, null, condition,
                        page);

                List<OptionalColumn> optionalColumns = CreditConcernedTableFieldsEnum.getOptionalColumns();

                ExcelUtil.downloadExcel(response, tableList, "信用关注列表", "信用关注列表", showColumns, optionalColumns);

            } else {

                ExceptionLogger.error("CreditConcernedController#export", "未获取到当前用户信息！");
            }

        } else {

            ExceptionLogger.error("CreditConcernedController#export", "未获取到当前用户信息！");
        }

    }

    @RequestMapping("/exportTemplate.json")
    public void exportTemplate(HttpServletResponse response) throws IOException {

        FileUtils.downloadFile(this.getClass().getResource("/template.xlsx").getPath(), response);

    }

    @RequestMapping("/getDetail.json")
    public RestServiceResult<Object> getDetail(@RequestParam(value = "tybm") String tybm,
                                               @RequestParam(value = "id") int id, @RequestParam(value = "kId") String kId, HttpServletRequest request) {

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        String username = "";
        String realName = "";
        long deptId = 0;
        long userId = 0;
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            userInfo = user.getData();

            if (null != userInfo) {

                username = userInfo.getUsername();

                realName = userInfo.getRealName();

                deptId = userInfo.getOfficeId();

                userId = userInfo.getId();
            } else {

                ExceptionLogger.error("CreditConcernedController#getDetail", "未获取到当前用户信息！");
            }

        } else {

            ExceptionLogger.error("CreditConcernedController#getDetail", "未获取到当前用户信息！");
        }

        Map<String, Object> detail = sContentService.getDetail(kId, tybm, "YZS", userInfo);

        shareLogService.add(1, (String) detail.get("category"), HttpServletHelper.getGuestIP(request), username,
                realName, deptId, tybm);

        sSearchService.addHistory(tybm, kId, userId);

        creditConcernedService.updateCheckStatus("Y", id, null);

        return new RestServiceResult<Object>(detail.get("results"));

    }

    @RequestMapping("/delete.json")
    public RestServiceResult<Object> delete(@RequestParam(value = "id") int id) {

        creditConcernedService.deletById(id);

        return new RestServiceResult<Object>();

    }

    @RequestMapping("/addMessage.do")
    public RestServiceResult<Object> addMessage() {

        List<Map<String, Integer>> changedSubjects = creditConcernedService.getSubjectChangedSubscriber();

        if (!CollectionUtils.isEmpty(changedSubjects)) {

            creditConcernedService.updatePushStatus("Y", changedSubjects);

            List<MsgContentEntity> msgs = new ArrayList<MsgContentEntity>(changedSubjects.size());

            for (Map<String, Integer> changedSubject : changedSubjects) {

                assembleSysMsgInfo(msgs, changedSubject);

            }

            remoteBaseService.sendMsg(msgs, null);

        }

        return new RestServiceResult<Object>();

    }

    /**
     * @param msgs
     * @param changedSubject
     * @return
     */
    void assembleSysMsgInfo(List<MsgContentEntity> msgs, Map<String, Integer> changedSubject) {
        MsgContentEntity entity = new MsgContentEntity();
        entity.setMsgTitle("信用关注");
        entity.setMsgType(4);
        entity.setLinkUrl("/bigData/creditConcern/index");
        List<MsgDetailEntity> detailList = new ArrayList<MsgDetailEntity>(1);
        MsgDetailEntity detail = new MsgDetailEntity(1, changedSubject.get("userId"));
        detailList.add(detail);
        entity.setDetails(detailList);
        String msg = "你关注的企业信用信息已发生变动。请关注。";
        entity.setMsgContent(msg);
        msgs.add(entity);

    }
    
    @RequestMapping("/addXygz.json")
	  public RestServiceResult<Object> addXygz(@RequestParam(value = "json", defaultValue = "", required = true) String json,
			  HttpServletRequest request) {
		 RestServiceResult<Object> res = new RestServiceResult<Object>();
		 
		 String token = HttpServletHelper.getUserToken(request);
		 RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
			SysUser userInfo = null;
			if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
				userInfo = user.getData();
				if (null == userInfo || userInfo.getId() <= 0) {
					res.setCode(RestServiceResult.CODE_UNKNOW);
					res.setMsg("系统异常，请稍后再试！");
					ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
					return res;
				}
			} else {
				res.setCode(user.getCode());
				res.setMsg(user.getMsg());
				return res;
			}
			
		 if (json == null || "".equals(json)) {
	            throw new ServiceException("选择企业不得为空");
	        }
		 
		 try {
			 List<XyjgDrqydf> xyjgDrqydfList = JSONArray.parseArray(json, XyjgDrqydf.class);
			 	
			 for(XyjgDrqydf xyjgDrqydf: xyjgDrqydfList){
				 
				 ConcernedSubject record = new ConcernedSubject();
				 
				 record.setUserId(userInfo.getId());
				 record.setSubjectName(xyjgDrqydf.getQymc());
				 record.setLevel("S");
				 creditConcernedService.add(record);
			 }
			 
			} catch (Exception e) {
				res.setCode(RestServiceResult.CODE_UNKNOW);
				res.setMsg("系统异常");
			}
		 return res;
	 }

}
